# Importing Data
AUSTRIA <- read_excel("C:/Users/Biniam/Desktop/Documents/Academic/Thesis/Analysis Folder/Excel Files/UAE/Austria.xlsx")

# Checking the Imported Data
View(AUSTRIA)

# Creating Time Series Data
AUSTRIA_ts <- ts(AUSTRIA, start=c(2004,1), end=c(2019,06), frequency=12)

# Viewing and Checking the Created Time Series Data
AUSTRIA_ts
sum(is.na(AUSTRIA_ts))
library(forecast)
AUSTRIA_ts <- tsclean(AUSTRIA_ts)

# Step – 1 of the Box-Jenkins Methodology (Identification: Plotting the Time Series Data)
plot(AUSTRIA_ts)
plot(aggregate(AUSTRIA_ts,FUN=mean))

# Decomposing
AUSTRIA_ts_decomp <- decompose(AUSTRIA_ts)
plot(AUSTRIA_ts_decomp)

# Testing for Stationarity
acf(AUSTRIA_ts, lag.max=20)
pacf(AUSTRIA_ts, lag.max=20)

# To see any seasonal effect
boxplot(AUSTRIA_ts~cycle(AUSTRIA_ts))

# To remove trend effect
AUSTRIA_ts_diff <- diff(AUSTRIA_ts)
plot(AUSTRIA_ts_diff)

# To remove variance effect
AUSTRIA_ts_log <- log(AUSTRIA_ts)
plot(AUSTRIA_ts_log)

# To remove both (Trend and Variance) effects
AUSTRIA_ts_both <- diff(log(AUSTRIA_ts))
plot(AUSTRIA_ts_both)


# Dealing with ACF and PACF
install.packages("tseries")
library(tseries)
acf(AUSTRIA_ts, lag.max=20)
acf(log(AUSTRIA_ts), lag.max=20)
acf(diff(AUSTRIA_ts), lag.max=20)
acf(diff(log(AUSTRIA_ts)), lag.max=20)
pacf(AUSTRIA_ts, lag.max=20)
pacf(log(AUSTRIA_ts), lag.max=20)
pacf(diff(AUSTRIA_ts), lag.max=20)
pacf(diff(log(AUSTRIA_ts)), lag.max=20)

# Step-2 of the Box-Jenkins Methodology (Estimating the appropriate model)
AUSTRIA_ts_model <- auto.arima(AUSTRIA_ts)
AUSTRIA_ts_model
AUSTRIA_ts_model <- auto.arima(AUSTRIA_ts, ic="aic", trace = TRUE)
AUSTRIA_ts_model

# Step-3 of the Box-Jenkins Methodology (Diagnosis Checking)
library(tseries)
plot.ts(AUSTRIA_ts_model$resid)
acf(AUSTRIA_ts_model$residuals, main='ACF Residual')
pacf(AUSTRIA_ts_model$residuals, main='ACF Residual')
Box.test(AUSTRIA_ts_model$resid, lag=20, type="Ljung-Box")

# Forecasting
options(max.print=1000000)
library(forecast)
AUSTRIA_ts_forecast <- forecast (AUSTRIA_ts_model, level=c(95), h=258)
plot(AUSTRIA_ts_forecast)
AUSTRIA_ts_forecast             


write.table(AUSTRIA_ts_forecast, file="Austria_TSA.csv", sep=",")
